package servlets;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import business.LaCorunaDelegator;

import dto.ItemPedidoDTO;
import dto.PedidoDTO;
import dto.xml.XMLPalcDTO;

import xml.XMLParser;
/**
 * Servlet implementation class for Servlet: PalcManager
 *
 */
 public class PalcManager extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
   static final long serialVersionUID = 1L;
   private File tmpDir;
   private File destinationDir;  
   private PropertiesConfiguration configuration;
   private static final String PALC_RESULT = "/WEB-INF/jsp/palc_result.jsp";
   
   public PalcManager() {
	   super();
	   try{
		   configuration = new PropertiesConfiguration("configWeb.properties");
		   String path = configuration.getString("xml.palc.dir"); // PONER HARDCODEADO EN EL configWeb.properties, EL directorio en donde esta alojado el XML del Palc que nos van a subir.
		   tmpDir = new File(path);
		   destinationDir = new File(path);

		   if(!tmpDir.isDirectory()){
			   throw new ServletException(path + " is not a directory");
		   }else{
			   destinationDir = new File(path);
		   }

		   if(!destinationDir.isDirectory()) {
			   throw new ServletException(path + " is not a directory");
		   }			
	   }catch (Exception e) {
		   e.printStackTrace();
	   }
   }   
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	} 
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// a implementar commons
		doProcess(request,response);
	}  	
	
	private void doProcess(HttpServletRequest request, HttpServletResponse response) {
		try {
			File f = parseAndSaveUploadedFile(request);
			XMLParser parser = new XMLParser();
			
			XMLPalcDTO palc = (XMLPalcDTO) parser.parseToObject(f);
			
			LaCorunaDelegator delegator = LaCorunaDelegator.getInstance();
			try{
				PedidoDTO pedido= delegator.nuevoPalc(palc);
				System.out.println("El pedido es el de id = " + pedido.getRef());
				request.setAttribute("pedido", pedido);
				request.setAttribute("items", pedido.getItemsPedidos());
				getServletContext().getRequestDispatcher(PALC_RESULT).forward(request, response);
			}catch (Exception e) {
				e.printStackTrace();
				getServletContext().getRequestDispatcher(PALC_RESULT).forward(request, response);
			}
			getServletContext().getRequestDispatcher(PALC_RESULT).forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}


	
	private File parseAndSaveUploadedFile(HttpServletRequest request) {
		DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
		fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB
		fileItemFactory.setRepository(tmpDir);
		//System.out.println("+++++++ ESTE ES EL DIRECTORIO DEL PALC: " + request.getParameter("palc"));
		ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);

		/*
		 * Parse the request
		 */
		File file=null;
		List items;
		try {
			items = uploadHandler.parseRequest(request);
			Iterator itr = items.iterator();
			if (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				if (!item.isFormField()) {
					file = new File(destinationDir, item.getName());
					item.write(file);
					System.out.println("El archivo que se subio es: " + file.getAbsolutePath() + " - " + file.getName());
					return file;
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return file;
	}

}